package com.markhsiu.proxy;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by Mark Hsiu on 2017/8/5.
 */
public class MittyAcceptor extends Thread{
    private static final Logger logger = Logger.getLogger(MittyAcceptor.class);

    private Selector selector;
    private ServerSocketChannel serverChannel;


    public MittyAcceptor(ServerSocketChannel serverChannel) throws IOException {
        selector = Selector.open();
        this.serverChannel = serverChannel;
        serverChannel.register(selector, SelectionKey.OP_ACCEPT, this);
    }

    @Override
    public void run() {
        while(!Thread.interrupted()){
            try {
                select();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void select() throws IOException {
        int opsKey = selector.selectNow();
        if(opsKey > 0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
                SelectionKey key  = iterator.next();
                if(key.isAcceptable()){
                    SocketChannel socketChannel = serverChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    logger.info(" accept ... ");
                }
            }
            selectionKeys.clear();
        } else {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
